package com.yb.guigu.pick.security.filter;

import com.yb.guigu.pick.security.bean.GuiguPickUserRequest;
import com.yb.guigu.pick.security.generator.AuthenticationTokenGenerator;
import com.yb.guigu.pick.core.util.StreamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 14:44
 * FileName: GuiguPickAuthenticationFilter
 * Description:
 */
public class GuiguPickAuthenticationProcessingFilter extends GuiguPickAbstractAuthenticationProcessingFilter {
    private static final String DEFAULT_PROCESSING_URL="/login";

    @Autowired
    private AuthenticationTokenGenerator authenticationTokenGenerator;
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher(DEFAULT_PROCESSING_URL,
            "POST");



    public GuiguPickAuthenticationProcessingFilter(AuthenticationManager authenticationManager){
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER,authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

        GuiguPickUserRequest userRequest = StreamUtil.readAsObject(GuiguPickUserRequest.class, request.getInputStream());

        if(Objects.isNull(userRequest)){
            userRequest=new GuiguPickUserRequest();
        }
        Authentication authentication = authenticationTokenGenerator.unauthenticated(userRequest);

        if(Objects.isNull(authentication)){
            throw new UsernameNotFoundException("不支持的登陆类型，loginType");
        }

        return getAuthenticationManager().authenticate(authentication);
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        super.successfulAuthentication(request, response, chain, authResult);
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        super.unsuccessfulAuthentication(request, response, failed);
    }
}
